﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Text;

namespace Data.Abstract
{
    public abstract class BaseSqlDal: IDisposable
    {
        public SQLiteConnection Connection;
        public BaseSqlDal(SQLiteConnection Conn)
        {
            this.Connection = Conn;
        }

        protected void Load()
        {
            CheckDal();
        }

        bool _ConnectionCreatedHere = false;
        private void CheckDal()
        {
            if (Connection == null)
            {
                //throw new ApplicationException("Conn is null");
                // perdon por esto, pero me parecio copado que lo haga.
                // G: No hay problema mientras se use la interfaz IDisposable. Esto aplica tanto para aca como para el IObject
                this.Connection = new Data.Configuration.Context().GetNewDatabaseConnection();
                if (this.Connection.State != System.Data.ConnectionState.Open)
                {
                    this.Connection.Open();
                }
                _ConnectionCreatedHere = true;
            }
            else
            {
                if (String.IsNullOrEmpty(Connection.ConnectionString))
                {
                    this.Connection = new Data.Configuration.Context().GetNewDatabaseConnection();
                    _ConnectionCreatedHere = true;
                }
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_ConnectionCreatedHere)
            {
                if (this.Connection.State != System.Data.ConnectionState.Closed) this.Connection.Close();
                this.Connection.Dispose();
            }
        }

        #endregion
    }
}
 